from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import json

app = Flask(__name__)


# http://127.0.0.1:5000/index
@app.route('/index')
def index():
    return render_template('index.html')


# http://127.0.0.1:5000/message
WEBSOCKET_LIST = []


@app.route('/message')
def message():
    wsock = request.environ.get('wsgi.websocket')
    WEBSOCKET_LIST.append(wsock)
    print(  WEBSOCKET_LIST)
    if not wsock:
        return '400'
    while True:
        try:
            message1 = wsock.receive()
            print(message1)
        except WebSocketError:
            break
        print ("现有连接用户：%s" % (len(WEBSOCKET_LIST)))
        if message1:
            for WE in WEBSOCKET_LIST:
                try:
                    wsock.send(message)
                except WebSocketError:
                    print('某用户已断开连接')


    # try:
        # if request.environ.get('wsgi.websocket'):
            # ws = request.environ['wsgi.websocket']

            # if not ws:
                # print('http')
                # return '您使用的是Http协议'
            # while True:
                
                # cid = ws.receive()  # 接收信息
                # print(cid)
                # ws.send(cid)
        # else:
            # abort(400,'not!')
    # except:
        # return "not"


if __name__ == '__main__':
    http_server = WSGIServer(('127.0.0.1',5000 ), app, handler_class=WebSocketHandler)
    http_server.serve_forever()
